//
//  KQMessageAnswerContentView.swift
//  KangYunYouJia
//
//  Created by zhouxiang on 2021/3/10.
//  Copyright © 2021 kqdc. All rights reserved.
//

import UIKit
import YYText

class KQMessageAnswerContentView: UIView, KQMessageContentViewType, YYTextViewDelegate {

    public override init(frame: CGRect) {
        super.init(frame: frame)
        _commonInit()
    }
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        _commonInit()
    }
    
    open func apply(_ message: KQMessageType) {
        _message = message
        guard let content = message.content as? KQMessageAnswerContent else {
            return
        }
        _delegate = content.delegate
        
        self.question = content.model.question
        self.answer = content.kqAttributeText
        
        self.titleLabel.text = self.question
        
        self.answerTextView.attributedText = self.answer
        
    }
    
    func textView(_ textView: YYTextView, didTap highlight: YYTextHighlight, in characterRange: NSRange, rect: CGRect) {
    
        let type = YYTextNSTextCheckingTypeFromUIDataDetectorType(textView.dataDetectorTypes)
        let detector = try? NSDataDetector.init(types: type.rawValue)
        let textAtt = textView.attributedText?.attributedSubstring(from: characterRange)
        let text = textAtt?.string ?? ""
        detector?.enumerateMatches(in: text, options: [], range: NSMakeRange(0, text.count), using: { (result, flags, stop) in
            if result?.resultType == NSTextCheckingResult.CheckingType.link {
                
                if let url = URL(string: text) {
                    if UIApplication.shared.canOpenURL(url) {
                        UIApplication.shared.openURL(url)
                    } else {
                        if let newUrl = URL(string: "https://" + text) {
                            UIApplication.shared.openURL(newUrl)
                        }
                    }
                }
                
            } else if result?.resultType == NSTextCheckingResult.CheckingType.phoneNumber {
                if let newUrl = URL(string: "tel://" + text) {
                    UIApplication.shared.openURL(newUrl)
                }
            }
        })
        
    }
    
    /// 获取高度
    open class func getTotalSize(question: String?, answer: NSAttributedString) -> CGSize {
        let questionLeft: CGFloat = 10 + 20 + 5
        let questionRight: CGFloat = 10
        let questionSize = KQChatUtils.shared().sizeThatFits(CGSize(width: 250.0 - questionLeft - questionRight, height: CGFloat.greatestFiniteMagnitude), font: UIFont(name: KQCHAT_FONT_MEDIUM_NAME, size: 15)!, text: question ?? "未知")
        let questionWidth = questionSize.width + questionLeft + questionRight
        
        let answerLeft: CGFloat = 10
        let answerRight: CGFloat = 10
        let answerSize = answer.boundingRect(with: CGSize(width: Double(250.0 - answerLeft - answerRight), height: Double(MAXFLOAT)), options: [.usesLineFragmentOrigin,.usesFontLeading], context: nil)
        //let answerSize = KQChatUtils.shared().sizeThatFits(CGSize(width: 250.0 - answerLeft - answerRight, height: CGFloat.greatestFiniteMagnitude), attribute: answer)
        let answerWidth = answerSize.width + answerLeft + answerRight
        return CGSize(width: 250.0, height: questionSize.height + answerSize.height + 20.0 + 20.0 + 3.0)
    }
    
    func _commonInit() {
        
        self.isUserInteractionEnabled = true
        self.addSubview(self.imageView)
        self.addSubview(self.titleLabel)
        
        self.imageView.snp.makeConstraints { (make) in
            make.left.equalTo(10)
            make.width.height.equalTo(20)
            make.centerY.equalTo(self.titleLabel.snp.centerY)
        }
        
        self.titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(10)
            make.left.equalTo(self.imageView.snp.right).offset(5)
            make.right.equalToSuperview().offset(-10)
        }
        
        self.addSubview(self.line)
        self.line.snp.makeConstraints { (make) in
            make.top.equalTo(self.titleLabel.snp.bottom).offset(10)
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.height.equalTo(1.0 / UIScreen.main.scale)
        }
        
        self.addSubview(self.answerTextView)
        self.answerTextView.snp.makeConstraints { (make) in
            make.top.equalTo(self.line.snp.bottom).offset(10)
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview().offset(-10)
        }
        
    }
    
    weak var _delegate: KQMessageDelegate?
    private var _message: KQMessageType!
    var question: String?
    var answer: NSAttributedString?
    
    
    lazy var imageView: UIImageView = {
        let imageView = UIImageView.init(frame: CGRect.zero)
        imageView.image = UIImage(named: "kq_chat_question_icon.png")
        return imageView
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel.init(frame: CGRect.zero)
        label.textColor = KQCHAT_COLOR(12, 157, 196)
        label.font = UIFont(name: KQCHAT_FONT_MEDIUM_NAME, size: 15)
        label.numberOfLines = 0
        return label
    }()
    
    lazy var line: UIImageView = {
        let imageView = UIImageView.init(frame: CGRect.zero)
        imageView.backgroundColor = KQCHAT_COLOR(230, 230, 230)
        return imageView
    }()
    
    lazy var answerTextView: YYTextView = {
        let textView = YYTextView.init()
        textView.isScrollEnabled = false
        textView.dataDetectorTypes = [.phoneNumber, .link]
        textView.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        textView.delegate = self
        textView.isEditable = false
        textView.textColor = .black
        return textView
    }()
    
}
